# -*- coding:utf-8 -*-
# Author:XG

from flask import Flask
from .settings.dev import DevConfig
from .settings.prod import ProdConfig
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager, Command
from flask_migrate import Migrate, MigrateCommand
from flask_session import Session
from .utils.log import set_log
from flask_jsonrpc import JSONRPC
from flask_jsonrpc.site import JSONRPCSite

# 创建jsonrpc实例对象
jsonrpc_v1 = JSONRPC(app=None, service_url='/api/v1', site=JSONRPCSite(), enable_web_browsable_api=True)
jsonrpc_v2 = JSONRPC(app=None, service_url='/api/v2', site=JSONRPCSite(), enable_web_browsable_api=True)

config = {
    'dev': DevConfig,
    'prod': ProdConfig
}

# 创建数据库链接对象
db = SQLAlchemy()

def init_app(config_name):
    '''项目初始化功能'''
    app = Flask(__name__)

    # 终端脚本工具
    app.manager = Manager(app)

    # 启用数据迁移工具
    Migrate(app, db)
    # 添加数据迁移的命令到终端脚本工具中
    app.manager.add_command('db', MigrateCommand)

    # 设置配置类
    Config = config.get(config_name)

    # 加载配置
    app.config.from_object(Config)

    # 配置数据库链接
    db.init_app(app)

    # 开启session功能
    Session(app)

    # 启动日志
    set_log(Config)

    # jsonrpc注册到app应用对象中
    jsonrpc_v1.init_app(app)
    jsonrpc_v2.init_app(app)

    return app












